﻿using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;

namespace Super.Admin.Utils
{
    public class IpAddressHelper
    {
        public static readonly Lazy<IpAddressHelper> _instance = new Lazy<IpAddressHelper>(() => new IpAddressHelper());
        public static IpAddressHelper Instance => _instance.Value;
        private IpAddressHelper() { }
        /// <summary>
        /// 获取所有IP
        /// </summary>
        /// <returns></returns>
        public static List<string> GetAllLocalIPAddresses()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            return host.AddressList
                .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)
                .Select(ip => ip.ToString())
                .ToList();
        }
        /// <summary>
        /// 获取IPV4的IP
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string GetLocalIPv4Address()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("未找到IPv4地址");
        }
        /// <summary>
        /// 获取指定网口的IP
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetLocalIPAddressByInterface(NetworkInterfaceType type)
        {
            foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (item.NetworkInterfaceType == type && item.OperationalStatus == OperationalStatus.Up)
                {
                    foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            return ip.Address.ToString();
                        }
                    }
                }
            }
            return null;
        }
    }
}
